package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.model.mongo.UserLike;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    // 探花 -- 喜欢 ,不喜欢 ,保存或者更新 ,通用的方法
    public Boolean saveOrUpdate(Long userId, Long likeUserId, boolean isLike) {
        try{
            // 1:查询数据
            Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
            UserLike userLike = mongoTemplate.findOne(query, UserLike.class);
            // 2:如果不存在,直接保存
            if (userLike == null){
                userLike = new UserLike();
                userLike.setUserId(userId);
                userLike.setLikeUserId(likeUserId);
                userLike.setCreated(System.currentTimeMillis());
                userLike.setUpdated(System.currentTimeMillis());
                userLike.setIsLike(isLike);
                mongoTemplate.save(userLike);
            }
            // 3:如果存在,更新数据
            Update update = Update.update("isLike",isLike).set("updated",System.currentTimeMillis());
            // 3个参数, 1:更新条件, 2:更新字段  3:操作的实体类
            mongoTemplate.updateFirst(query,update,UserLike.class);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    // 喜欢我的
    public Integer likMe(Long userId, boolean isLike) {
        Query query = Query.query(Criteria.where("likeUserId").is(userId).and("isLike").is(isLike));
        Long count = mongoTemplate.count(query, UserLike.class);
        return count.intValue();
    }

    // 我喜欢的
    public Integer myLike(Long userId, boolean isLike) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("isLike").is(isLike));
        Long count = mongoTemplate.count(query, UserLike.class);
        return count.intValue();
    }

    // 互相喜欢的
    public Integer eachLoveCount(Long userId, boolean isLike) {
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("isLike").is(isLike));
        List<UserLike> list = mongoTemplate.find(query, UserLike.class);
        List<Long> likeUserId = CollUtil.getFieldValues(list, "likeUserId", Long.class);
        Query query1 = Query.query(Criteria.where("userId").in(likeUserId).and("isLike").is(isLike)
                .and("likeUserId").is(userId));
        Long count = mongoTemplate.count(query1, UserLike.class);
        return count.intValue();
    }
}
